package com.example.demo.config;

import com.alibaba.fastjson.JSON;
import com.example.demo.entity.response.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * @version 1.0
 * @Author: LJP
 * @Description: 统一返回处理的实现逻辑
 * @Date: Created in 18:02 2021/12/1
 */
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        Method method = methodParameter.getMethod();
        return null != method && Void.class != method.getReturnType();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body == null) {
            //当 body 返回类型为 string 并且为null会出现 java.lang.ClassCastException: Result cannot be cast to java.lang.String,则封装ResultMsg对象并转换为String返回*/
            if (methodParameter.getParameterType().getName().equals("java.lang.String")) {
                return JSON.toJSON(Result.success()).toString();
            }
            return Result.success();
        }
        //当 body Result(统一封装返回对象),则直接返回
        if (body instanceof Result) {
            return body;
        }
        ///当 o 为string 则特殊处理 java.lang.ClassCastException: Result cannot be cast to java.lang.String,封装ResultMsg对象并转换为String返回
        if (body instanceof String) {
            return JSON.toJSON(Result.success().data(body)).toString();
        }
        return Result.success().data(body);
    }
}
